package com.bensonbasement.snorflux.client;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;


public class ChatPanel extends JPanel implements ActionListener {
	public interface ChatPanelHandler {
		public void handleTextEntered(String text);
		public void handleTextCanceled();
	}
	
	private final JTextArea messageArea;
	private final JTextField chatTextField;
	private final ChatPanelHandler handler;
	
	private boolean enabled = true;
	
	public ChatPanel(final ChatPanelHandler handler) {
		this.handler = handler;
		
		this.messageArea = new JTextArea(5,50);
		this.messageArea.setLineWrap(true);
		this.messageArea.setEditable(false);
		JScrollPane textScrollPane = new JScrollPane(this.messageArea);
		
		this.chatTextField = new JTextField(20);
		this.chatTextField.addActionListener(this);
		chatTextField.addKeyListener(new KeyListener() {
			@Override
			public void keyPressed(KeyEvent e) {
				if (e.getKeyCode() == KeyEvent.VK_ESCAPE) {
					handler.handleTextCanceled();
				}
			}
			
			@Override
			public void keyReleased(KeyEvent arg0) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void keyTyped(KeyEvent arg0) {
				// TODO Auto-generated method stub
				
			}
			
		});
		
		this.setLayout(new BorderLayout());
		this.add(this.chatTextField, BorderLayout.SOUTH);
		this.add(textScrollPane, BorderLayout.CENTER);
	}
	
    public void actionPerformed(ActionEvent evt) {
        String text = this.chatTextField.getText();
        if (text.trim().length() > 0) {
        	this.handler.handleTextEntered(text);
        }
        this.chatTextField.setText("");
    }
    
    public void postMessage(String message) {
    	if ( ! this.messageArea.getText().equals("")) {
    		this.messageArea.append("\n");
    	}
    	this.messageArea.append(message);
        //Make sure the new text is visible, even if there
        //was a selection in the text area.
        this.messageArea.setCaretPosition(this.messageArea.getDocument().getLength());
    }

	public boolean isEnabled() {
		return enabled;
	}

	public void setEnabled(boolean enabled) {
		this.enabled = enabled;
		this.chatTextField.setEnabled(enabled);
	}
	
	public void clearMessages() {
		this.messageArea.setText("");
	}
	
	public void focusChatTextField() {
		this.chatTextField.requestFocusInWindow();
	}
}
